<?php

namespace App\Domain\ChannelBusiness\Services;

use App\Domain\Account\Dao\AccountDao;
use App\Domain\ChannelBusiness\Dao\ChannelBusinessDao;
use App\Domain\ChannelBusiness\Models\ChannelBusinessModel;
use App\Exceptions\BadRequestException;
use App\Supports\Constant\PaginationConst;
use App\Supports\Formatter\ResponseFormatter;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Builder;

class ChannelBusinessService
{
    /**
     * 生成盐值
     * @return string
     */
    public function generateSalt()
    {
        return \Str::random(16);
    }

    /**
     * 加密密码
     * @param $password
     * @param $salt
     * @return string
     */
    public function encryptionPassword($password, $salt)
    {
        return md5($password . $salt);
    }

    /**
     * 创建渠道商
     * @param $param
     * @return array
     * @throws \Exception
     */
    public function create(array $param)
    {
        $channelDao = new ChannelBusinessDao();
        $data = $channelDao->findByName($param['name']);
        if ($param['name'] === $data['name']) {
            throw new BadRequestException('渠道商已存在');
        }
        DB::beginTransaction();
        try {
            $result = $channelDao->create([
                'name' => $param['name'],
                'type' => $param['type'],
                'phone' => $param['phone'],
                'contacts' => $param['contacts'],
                'address' => $param['address'],
                'term_start' => $param['term_start'],
                'term_end' => $param['term_end'],
                'status' => $param['status'],
                'salesman' => $param['salesman'],
                'province' => $param['province'],
                'city' => $param['city'],
                'area' => $param['area'],
                'account' => $param['account'],
                'is_open' => $param['is_open'],
            ]);
            if ($param['is_open'] == 1) {
                $accountDao = new AccountDao();
                $data = $accountDao->findByAccount($param['account']);
                if ($param['account'] === $data['account']) {
                    throw new BadRequestException('账号已存在');
                }
                if ($param['phone'] === $data['phone']) {
                    throw new BadRequestException('手机号已存在');
                }
                $res = $accountDao->create([
                    'id' => create_uuid(),
                    'name' => $param['name'],
                    'phone' => $param['phone'],
                    'validity_time' => $param['term_end'],
                    'status' => '1',
                    'salt' => $salt = $this->generateSalt(),
                    'account' => $param['account'],
                    'roleName' => '',
                    'password' => md5('12345678' . $salt)
                ]);
                if (empty($res)) {
                    throw new BadRequestException('账号添加失败');
                }
            }
            if (empty($result)) {
                throw new BadRequestException('渠道商添加失败');
            }

            DB::commit();
        } catch (\Throwable $e) {
            DB::rollBack();
            throw new \Exception($e->getMessage(), $e->getCode(), $e);
        }
        return [];
    }

    /**
     * 渠道商列表
     * @param $params
     * @return LengthAwarePaginator|Builder[]|Collection
     */
    public function list($params)
    {
        $query = ChannelBusinessModel::query()
            ->select('channel_business.*')
            ->where('channel_business.state', 1);
        $query = $query->where(function (Builder $query) use ($params) {
            if (isset($params['name']))
                $query->where('name', 'like', "%{$params['name']}%");
            if (isset($params['phone']))
                $query->where('phone', 'like', "%{$params['phone']}%");
            if (isset($params['contacts']))
                $query->where('contacts', 'like', "%{$params['contacts']}%");
            if (isset($params['type']))
                $query->where('type', $params['type']);
            if (isset($params['province']))
                $query->where('province', $params['province']);
            if (isset($params['city']))
                $query->where('city', $params['city']);
            if (isset($params['area']))
                $query->where('area', $params['area']);
            if (isset($params['term_start']))
                $query->where('term_start',">=", $params['term_start']);
            if (isset($params['term_end']))
                $query->where('term_end', "<=",$params['term_end']);
            if (isset($params['status']))
                $query->where('status', $params['status']);
        });
        if (isset($params['pageSize']) && isset($params['currentPage'])) {
            return $query->paginate($params['pageSize'], ['*'], 'page', $params['currentPage']);
        } else {
            return $query->get();
        }
    }


    //修改渠道商
    function updateChannel($param)
    {
        $channelDao = new ChannelBusinessDao();
        $channel = $channelDao->findById($param['id']);
        if (empty($channel)) {
            throw new BadRequestException('渠道商不存在');
        }
        DB::beginTransaction();
        try {
            if ($param['is_open'] == 1) {
                $channelDao = new ChannelBusinessDao();
                $channel = $channelDao->findById($param['id']);
                $accountDao = new AccountDao();
                $account = $accountDao->findByAccount($channel['account']);

                if (empty($account)) {
                    throw new BadRequestException('账号不存在');
                }

                $data = [
                    'name' => $param['name'],
                    'phone' => $param['phone'],
                    'validity_time' => $param['term_end'],
                    'status' => '1',
                    'salt' => $salt = $this->generateSalt(),
                    'account' => $param['account'],
                    'roleName' => '',
                ];
                $res = $accountDao->update($account, $data);
                if (empty($res)) {
                    throw new BadRequestException('账号修改失败');
                }
            }
            $data = [
                'name' => $param['name'],
                'type' => $param['type'],
                'phone' => $param['phone'],
                'contacts' => $param['contacts'],
                'address' => $param['address'],
                'term_start' => $param['term_start'],
                'term_end' => $param['term_end'],
                'status' => $param['status'],
                'salesman' => $param['salesman'],
                'province' => $param['province'],
                'city' => $param['city'],
                'area' => $param['area'],
                'account' => $param['account'],
                'is_open' => $param['is_open'],
            ];
            $result = $channelDao->update($channel, $data);

            if (empty($result)) {
                throw new BadRequestException('渠道商修改失败');
            }

            DB::commit();
        } catch (\Throwable $e) {
            DB::rollBack();
            throw new \Exception($e->getMessage(), $e->getCode(), $e);
        }
        return [];
    }

    //删除渠道商
    function del($id)
    {
        DB::beginTransaction();
        try {
            $channelDao = new ChannelBusinessDao();
            $account = $channelDao->findById($id);
            $accountDao = new AccountDao();
            $res = $accountDao->findByAccount($account['account']);
            $result = $accountDao->del($res['id']);
            if (empty($result)) {
                throw new BadRequestException('账号删除失败');
            }
            $data = $channelDao->del($id);
            if (empty($data)) {
                throw new BadRequestException('账号删除失败');
            }
            DB::commit();
        } catch (\Throwable $e) {
            DB::rollBack();
            throw new \Exception($e->getMessage(), $e->getCode(), $e);
        }

        return [];
    }

    //修改接口
    function updateEquipment($param)
    {
        $channelDao = new ChannelBusinessDao();
        $channel = $channelDao->findById($param['id']);
        $data = ['data_upload_interface' => $param['data_upload_interface'],'is_interface'=>$param['is_interface']];
        $result = $channelDao->update($channel, $data);
        return $result;
    }

    public function ResetPassword($account)
    {
        $accountDao = new AccountDao();
        $account = $accountDao->findByAccount($account);
        $data = [
            'salt' => $salt = $this->generateSalt(),
            'password' => md5('12345678' . $salt)
        ];
        $account = $accountDao->update($account, $data);
        if ($account) {
            return [];
        }

    }

    public function findAll(){
        $channelDao = new ChannelBusinessDao();
        $channel = $channelDao->findAllName();
        return $channel;
    }
}
